import {fetchOrchards,createOrchard,updateOrchard,deleteOrchard} from '@/api/orchardinfo'

const state = {
  orchards: [],
  loading: false,
  error: null
};

const mutations = {
  SET_ORCHARDS(state, orchards) {
    state.orchards = orchards;
  },
  SET_LOADING(state, status) {
    state.loading = status;
  },
  SET_ERROR(state, error) {
    state.error = error;
  }
};

const actions = {
  fetchOrchards({ commit }) {
    return new Promise((resolve, reject) => {
      commit('SET_LOADING', true);
      commit('SET_ERROR', null);
      fetchOrchards().then(response => {
          console.log('获取果园信息成功:', response.data);
          commit('SET_ORCHARDS', response.data);
          resolve(response); // 可以选择是否需要解析响应
        })
        .catch(error => {
          console.error('获取果园信息失败:', error.message);
          commit('SET_ERROR', '加载果园信息失败，请稍后再试！');
          reject(error); // 传递错误到Promise的拒绝状态
        })
        .finally(() => {
          commit('SET_LOADING', false);
        });
    });
  },

  async createOrchard({ commit, dispatch }, data) {
    return new Promise(async (resolve, reject) => {
      try {
        commit('SET_LOADING', true);
        commit('SET_ERROR', null);

        await createOrchard(data);
        console.log('创建果园成功');
        await dispatch('fetchOrchards'); // 刷新果园列表

        resolve(); // 成功创建后解析Promise
      } catch (error) {
        console.error('创建果园失败:', error);
        commit('SET_ERROR', '创建果园失败，请稍后再试！');
        reject(error); // 创建失败后拒绝Promise
      } finally {
        commit('SET_LOADING', false);
      }
    });
  },

  async updateOrchard({ commit, dispatch }, { id, data }) {
    return new Promise(async (resolve, reject) => {
      try {
        commit('SET_LOADING', true);
        commit('SET_ERROR', null);

        await updateOrchard(id, data);
        console.log('更新果园成功');
        await dispatch('fetchOrchards'); // 刷新果园列表

        resolve(); // 成功更新后解析Promise
      } catch (error) {
        console.error('更新果园失败:', error);
        commit('SET_ERROR', '更新果园失败，请稍后再试！');
        reject(error); // 更新失败后拒绝Promise
      } finally {
        commit('SET_LOADING', false);
      }
    });
  },
  async deleteOrchard({ commit, dispatch }, id) {
    return new Promise(async (resolve, reject) => {
      try {
        commit('SET_LOADING', true);
        commit('SET_ERROR', null);

        await deleteOrchard(id);
        console.log('删除果园成功');
        await dispatch('fetchOrchards'); // 刷新果园列表

        resolve(); // 成功删除后解析Promise
      } catch (error) {
        console.error('删除果园失败:', error);
        commit('SET_ERROR', '删除果园失败，请稍后再试！');
        reject(error); // 删除失败后拒绝Promise
      } finally {
        commit('SET_LOADING', false);
      }
    });
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};